package com.dh.modules.system.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.dh.modules.system.dao.AdminDao;
import com.dh.modules.system.entity.Admin;
import com.dh.modules.system.service.AdminService;

@Service
public class AdminServiceImpl implements AdminService {

	@Autowired
	private AdminDao adminDao;

	@Override
	public List<Admin> findAdmin(String username) {
		return adminDao.findByUsername(username);
	}

	@Override
	public Admin findById(String adminId) {
		return adminDao.findOne(adminId);
	}

	@Override
	public void deleteById(String anotherAdminId) {
		Admin admin = this.findById(anotherAdminId);
		admin.setDeleted(true);
		adminDao.save(admin);
	}

	@Override
	public int updateById(Admin admin) {
		try {
			adminDao.save(admin);
			return 1;
		}catch (Exception e){
			return 0;
		}
	}

	@Override
	public void add(Admin admin) {
		adminDao.save(admin);
	}

	@Override
	public int countSelective(String username, Integer page, Integer pagesize, String sort, String order) {
		Page<Admin> allAdmin = selectAllAdmin(username, page, pagesize, sort, order);
		return allAdmin.getSize();
	}

	@Override
	public List<Admin> querySelective(String username, Integer page, Integer pagesize, String sort, String order) {
		Page<Admin> allAdmin = selectAllAdmin(username, page, pagesize, sort, order);
		return allAdmin.getContent();
	}

	@Override
	public Page<Admin> selectAllAdmin(String username, Integer page, Integer pagesize, String sort, String order) {
		Admin admin = new Admin();
		Example<Admin> example = Example.of(admin);
		if (StringUtils.isNotBlank(username)) {
			admin.setUsername(username);
		}
		Direction direction = Direction.ASC.toString().equals(order) ? Direction.ASC : Direction.DESC;
		Sort Sort = new Sort(direction, sort);
		PageRequest pageable = new PageRequest(page, pagesize, Sort);
		return adminDao.findAll(example, pageable);
	}

}
